/*
 * 文 件 名:  ServletFilter.java
 * 版    权:  Huawei Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  pWX14769
 * 修改时间:  2011-1-20
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.kuanrf.common.filter;

import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kuanrf.common.util.PropertyUtils;

/**
 * Filter
 * 
 * @author  zWX14769
 * @version  [版本号, 2011-1-20]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class PictureFilter implements Filter
{
    
    //图片防盗链白名单
    private String whiteNameList = "";
    
    /**
     * 允许的主机名
     */
    private Set<String> hostNames = new HashSet<String>(100);
    
    /**
     * 日志记录器
     */
    Log logger = LogFactory.getLog(this.getClass());
    
    /**
     * @param arg0
     * @throws ServletException
     */
    public void init(FilterConfig arg0) throws ServletException
    {
        //读取配置文件
        try
        {
            whiteNameList = PropertyUtils.getValue("file.picture.filter")
                    .toString();
        }
        catch (Exception e)
        {
            logger.error("图片防盗链加载配置文件失败，配置项为<file.picture.filter>");
            return;
        }
        //得到本机IP并放入到请允许访问的列表中
        String ip = null;
        String hostName = null;
        if (whiteNameList != null && whiteNameList.trim().length() > 0)
        {
            hostNames.addAll(Arrays.asList(whiteNameList.split(",")));
        }
        try
        {
            //循环得到本机IP
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements())
            {
                NetworkInterface networkInterface = enumeration.nextElement();
                if (networkInterface.isUp())
                {
                    Enumeration<InetAddress> addressEnumeration = networkInterface.getInetAddresses();
                    while (addressEnumeration.hasMoreElements())
                    {
                        InetAddress addr = addressEnumeration.nextElement();
                        ip = addr.getHostAddress().toString();
                        if (ip != null)
                        {
                            hostNames.add(ip);
                        }
                        hostName = addr.getHostName().toString();
                        if (hostName != null)
                        {
                            hostNames.add(hostName);
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            
        }
    }
    
    /**
     * 
     */
    public void destroy()
    {
        
    }
    
    /**
     * 请求过滤器
     * @param req
     * @param resp
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        
        String relativeURL = request.getServletPath();
        //------------------以下内容为防盗链
        //        //截取所有图片请求
        if (relativeURL.endsWith("gif") || relativeURL.endsWith("jpeg")
                || relativeURL.endsWith("jpg") || relativeURL.endsWith("png")
                || relativeURL.endsWith("bmp") || relativeURL.endsWith("GIF")
                || relativeURL.endsWith("JPEG") || relativeURL.endsWith("PNG")
                || relativeURL.endsWith("JPG") || relativeURL.endsWith("BMP"))
        {
            //如果请求头不为空
            String referer = request.getHeader("Referer");
            
            if (referer != null)
            {
                //得到请求的主机名
                String host = null;
                try
                {
                    URL url = new URL(relativeURL);
                    host = url.getHost();
                }
                catch (MalformedURLException e)
                {
                    return;
                }
                Pattern pattern = null;
                String host_ = null;
                boolean rs_ = false;
                Iterator<String> iterator = hostNames.iterator();
                //检查过来的请求Host是否合法
                while (iterator.hasNext())
                {
                    host_ = iterator.next();
                    pattern = Pattern.compile(host_);
                    Matcher mat = pattern.matcher(host);
                    rs_ = mat.find();
                    if (rs_)
                    {
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
            else
            {
                chain.doFilter(request, response);
                return;
                
            }
        }
        try
        {
            chain.doFilter(request, response);
        }
        catch (Exception e)
        {
            logger.error(e);
        }
        
    }
    
    /**
     * @return 返回 whiteNameList
     */
    public String getWhiteNameList()
    {
        return whiteNameList;
    }
    
    /**
     * @param 对whiteNameList进行赋值
     */
    public void setWhiteNameList(String whiteNameList)
    {
        this.whiteNameList = whiteNameList;
    }
    
}
